package com.project.dao.Impl;

import com.project.bean.CutPagBean;
import com.project.bean.ProductBean;
import com.project.dao.IProductDao;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
@Repository
public class ProductDaoImpl extends BaseDao implements IProductDao {
    @Override
    public CutPagBean<ProductBean> findByItem(int pageNo, String name) {
        CutPagBean<ProductBean> cutBean = new CutPagBean<>();
        String sql ="SELECT p.*,COUNT(s.pk_speakId) speakNum FROM t_product p LEFT JOIN t_speak s" +
                " ON p.pk_productId=s.fk_productId" ;
        String dynaSql=" where 1=1 ";
        if (name!=null&&name.length()!=0){
            dynaSql+= "and p_name LIKE '%"+name+"%'";
        }
        this.setConnection();
        try {
            ps=con.prepareStatement(sql+dynaSql+"GROUP BY p.pk_productId LIMIT ?,?");
            ps.setObject(1,(pageNo-1)*CutPagBean.PAGESIZE);
            ps.setObject(2,CutPagBean.PAGESIZE);
            rs=ps.executeQuery();
            while (rs.next()){
             cutBean.getList().add(this.getProduct());
            }
            ps=con.prepareStatement("select count(*) c from t_product"+dynaSql);
            rs= ps.executeQuery();
            if (rs.next()){
                cutBean.setCount(rs.getInt("c"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return cutBean;
    }

    private ProductBean getProduct() {
        ProductBean productBean = new ProductBean();
        try {
            productBean.setId(rs.getInt("pk_productId"));
            productBean.setName(rs.getString("p_name"));
            productBean.setPrice(rs.getInt("p_price"));
            productBean.setImgPath(rs.getString("p_imgPath"));
            productBean.setSpeakNUm(rs.getInt("speakNum"));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return productBean;
    }

    @Override
    public ProductBean findById(Integer id) {
        ProductBean product = null;
        this.setConnection();
        try {
            ps = con.prepareStatement("SELECT  p.*,COUNT(s.`pk_speakId`) speakNum FROM t_product p LEFT JOIN t_speak s " +
                    "ON p.`pk_productId`=s.`fk_productId` WHERE p.pk_productId=?");
            ps.setObject(1,id);
            rs = ps.executeQuery();
            if(rs.next()){
                product = this.getProduct();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            this.closeConnection();
        }
        return product;
    }
}
